package com.frank.fresh_mall.controller;

import com.frank.fresh_mall.common.ApiRestResponse;
import com.frank.fresh_mall.filter.UserFilter;
import com.frank.fresh_mall.model.vo.CartVO;
import com.frank.fresh_mall.service.CartService;
import io.swagger.annotations.ApiOperation;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.List;

/**
 * 购物车Controller
 */
@RestController
@RequestMapping("/cart")
public class CartController {
    @Resource
    private CartService cartService;

    @ApiOperation("购物车列表")
    @GetMapping("/list")
    public ApiRestResponse list() {
        // 内部获取用户ID，防止横向越权
        List<CartVO> cartVOList = cartService.list(UserFilter.currentUser.getId());
        return ApiRestResponse.success(cartVOList);
    }


    @ApiOperation("添加商品到购物车")
    @PostMapping("/add")
    public ApiRestResponse add(@RequestParam("productId") Integer productId,
                               @RequestParam("count") Integer count) {
        List<CartVO> cartVOList = cartService.add(UserFilter.currentUser.getId(),
                productId, count);
        return ApiRestResponse.success(cartVOList);
    }

    @ApiOperation("更新商品到购物车")
    @PostMapping("/update")
    public ApiRestResponse update(@RequestParam("productId") Integer productId,
                                  @RequestParam("count") Integer count) {
        List<CartVO> cartVOList = cartService.update(UserFilter.currentUser.getId(),
                productId, count);
        return ApiRestResponse.success(cartVOList);
    }

    @ApiOperation("删除商品到购物车")
    @PostMapping("/delete")
    public ApiRestResponse delete(@RequestParam("productId") Integer productId) {
        // 不能传入userId，cartId，否则可以删除别人的购物车
        List<CartVO> cartVOList = cartService.delete(UserFilter.currentUser.getId(),
                productId);
        return ApiRestResponse.success(cartVOList);
    }

    @ApiOperation("购物车商品选中/取消选中")
    @PostMapping("/select")
    public ApiRestResponse select(@RequestParam("productId") Integer productId,
                                  @RequestParam("selected") Integer selected) {
        List<CartVO> cartVOS = cartService.selectOrNot(UserFilter.currentUser.getId(), productId, selected);
        return ApiRestResponse.success(cartVOS);
    }

    @ApiOperation("购物车商品全选中/全不选中")
    @PostMapping("/selectAll")
    public ApiRestResponse selectAll(@RequestParam("selected") Integer selected) {
        List<CartVO> cartVOS = cartService.selectAllOrNot(UserFilter.currentUser.getId(), selected);
        return ApiRestResponse.success(cartVOS);
    }


}
